<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '任务详情',
  },
}
</route>
<template>
  <view class="task-detail-page">
    <!-- 自定义导航栏 -->
    <view
      class="custom-nav-bar bg-white p-4 border-b border-gray-200 flex justify-between items-center"
      :style="{ paddingTop: safeAreaInsets?.top + 'px' }"
    >
      <view class="flex items-center">
        <text class="i-fa-solid:chevron-left text-lg mr-2" @click="goBack"></text>
        <text class="text-xl font-semibold">任务详情</text>
      </view>
      <view class="flex space-x-4">
        <view class="text-gray-500" @click="handleEdit">
          <text class="i-fa-solid:edit"></text>
        </view>
        <view class="text-gray-500" @click="handleDelete">
          <text class="i-fa-solid:trash"></text>
        </view>
      </view>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 任务详情内容 -->
    <scroll-view v-else scroll-y class="task-detail-container">
      <view class="p-4">
        <!-- 任务标题和状态 -->
        <view class="flex items-center justify-between mb-6">
          <view class="flex-1">
            <text class="text-2xl font-semibold block mb-2">{{ task.title }}</text>
            <view class="flex items-center">
              <view
                class="task-status"
                :class="
                  task.completed ? 'bg-green-100 text-green-500' : 'bg-blue-100 text-blue-500'
                "
              >
                {{ task.completed ? '已完成' : '进行中' }}
              </view>
              <view
                class="task-priority ml-2"
                :class="{
                  'bg-red-100 text-red-500': task.priority === 'high',
                  'bg-orange-100 text-orange-500': task.priority === 'medium',
                  'bg-green-100 text-green-500': task.priority === 'low',
                }"
              >
                {{ getPriorityText(task.priority) }}
              </view>
            </view>
          </view>
          <view
            :class="['task-checkbox', task.completed ? 'checked' : '']"
            @click="toggleTaskStatus"
          >
            <text v-if="task.completed" class="i-fa-solid:check text-white"></text>
          </view>
        </view>

        <!-- 任务详情信息 -->
        <view class="bg-white rounded-lg shadow-sm p-4 mb-6">
          <view class="detail-item">
            <text class="detail-label">分类</text>
            <view
              class="category-tag"
              :style="{
                backgroundColor: task.category ? `${task.category.color}20` : 'rgba(158, 158, 158, 0.1)',
                color: task.category ? task.category.color : '#9e9e9e',
              }"
            >
              {{ task.category ? task.category.name : '未分类' }}
            </view>
          </view>

          <view class="detail-item">
            <text class="detail-label">日期</text>
            <text class="detail-value">{{ task.date || '未设置' }}</text>
          </view>

          <view class="detail-item">
            <text class="detail-label">时间</text>
            <text class="detail-value">{{ task.timeRange || '未设置' }}</text>
          </view>

          <view class="detail-item">
            <text class="detail-label">提醒</text>
            <view class="flex items-center">
              <text class="detail-value">{{ task.reminder ? '开启' : '关闭' }}</text>
              <switch
                :checked="task.reminder"
                @change="toggleReminder"
                color="#007aff"
                class="ml-2"
              />
            </view>
          </view>
        </view>

        <!-- 任务描述 -->
        <view class="bg-white rounded-lg shadow-sm p-4 mb-6">
          <text class="text-lg font-medium mb-3 block">描述</text>
          <text class="text-gray-700 leading-relaxed">{{ task.description || '无描述' }}</text>
        </view>

        <!-- 任务附件 -->
        <view class="bg-white rounded-lg shadow-sm p-4">
          <text class="text-lg font-medium mb-3 block">附件</text>
          <view v-if="task.attachments && task.attachments.length > 0">
            <view v-for="(file, index) in task.attachments" :key="index" class="attachment-item">
              <view class="attachment-icon">
                <text class="i-fa-solid:file text-blue-500"></text>
              </view>
              <view class="attachment-content">
                <text class="attachment-name">{{ file.name }}</text>
                <text class="attachment-size">{{ file.size }}</text>
              </view>
              <text class="i-fa-solid:download text-gray-400"></text>
            </view>
          </view>
          <view v-else class="py-4 text-center text-gray-500">
            <text>暂无附件</text>
          </view>
        </view>
        
        <!-- 创建和更新时间 -->
        <view class="mt-6 px-2">
          <view class="text-xs text-gray-500 mb-1">
            创建时间: {{ formatDateTime(task.createdAt) }}
          </view>
          <view class="text-xs text-gray-500">
            更新时间: {{ formatDateTime(task.updatedAt) }}
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script lang="ts" setup>
defineOptions({
  name: 'TaskDetailPage',
})

import { ref, onLoad, onShow } from 'vue'
import { taskService } from '@/services/task-service'
import type { Task } from '@/services/task-service'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 任务ID参数
const taskId = ref('')
// 加载状态
const loading = ref(false)

// 任务数据
const task = ref<Task>({
  id: '',
  title: '',
  categoryId: '',
  priority: 'medium',
  date: '',
  timeRange: '',
  completed: false,
  reminder: true,
  description: '',
  attachments: [],
  createdAt: '',
  updatedAt: ''
})

// 格式化日期时间
const formatDateTime = (dateTimeStr: string): string => {
  if (!dateTimeStr) return '未知时间';
  
  try {
    const date = new Date(dateTimeStr);
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  } catch (error) {
    return dateTimeStr;
  }
}

// 获取任务优先级文本
const getPriorityText = (priority: string) => {
  switch (priority) {
    case 'high':
      return '高优先级'
    case 'medium':
      return '中优先级'
    case 'low':
      return '低优先级'
    default:
      return '普通'
  }
}

// 切换任务状态
const toggleTaskStatus = async () => {
  if (!task.value.id) return
  
  const originalStatus = task.value.completed
  // 先在UI上立即显示变化
  task.value.completed = !task.value.completed
  
  // 更新数据库
  try {
    const success = await taskService.completeTask(task.value.id, task.value.completed)
    if (!success) {
      // 更新失败，回滚UI状态
      task.value.completed = originalStatus
      throw new Error('更新失败')
    }
  } catch (error) {
    console.error('更新任务状态失败:', error)
    uni.showToast({
      title: '更新失败',
      icon: 'none'
    })
    // 回滚UI状态
    task.value.completed = originalStatus
  }
}

// 切换提醒状态
const toggleReminder = async (e: any) => {
  if (!task.value.id) return
  
  const newValue = e.detail.value
  const originalValue = task.value.reminder
  
  // 先更新UI
  task.value.reminder = newValue
  
  // 然后更新数据库
  try {
    const success = await taskService.updateTask(task.value.id, {
      reminder: newValue
    })
    if (!success) {
      // 更新失败，回滚UI状态
      task.value.reminder = originalValue
      throw new Error('更新失败')
    }
  } catch (error) {
    console.error('更新提醒状态失败:', error)
    uni.showToast({
      title: '更新失败',
      icon: 'none'
    })
    // 回滚UI状态
    task.value.reminder = originalValue
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 编辑任务
const handleEdit = () => {
  if (!task.value.id) return
  
  uni.navigateTo({
    url: `/pages/task/edit?id=${task.value.id}`,
  })
}

// 删除任务
const handleDelete = () => {
  if (!task.value.id) return
  
  uni.showModal({
    title: '提示',
    content: '确定要删除该任务吗？',
    success: async (res) => {
      if (res.confirm) {
        // 执行删除操作
        loading.value = true
        try {
          const success = await taskService.deleteTask(task.value.id)
          if (success) {
            uni.showToast({
              title: '删除成功',
              icon: 'success',
            })
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          } else {
            throw new Error('删除失败')
          }
        } catch (error) {
          console.error('删除任务失败:', error)
          uni.showToast({
            title: '删除失败',
            icon: 'none',
          })
        } finally {
          loading.value = false
        }
      }
    },
  })
}

// 加载任务数据
const loadTaskData = async () => {
  if (!taskId.value) return
  
  loading.value = true
  try {
    const taskData = await taskService.getTaskById(taskId.value)
    if (taskData) {
      task.value = taskData
    } else {
      throw new Error('任务不存在')
    }
  } catch (error) {
    console.error('加载任务失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none',
    })
    setTimeout(() => {
      goBack()
    }, 1500)
  } finally {
    loading.value = false
  }
}

// 页面加载时，获取任务数据
onLoad((options) => {
  if (options && options.id) {
    taskId.value = options.id
    loadTaskData()
  }
})

// 页面显示时刷新数据
onShow(() => {
  if (taskId.value) {
    loadTaskData()
  }
})
</script>

<style lang="scss">
.task-detail-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f2f2f7;
}

.loading-container {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-text {
  font-size: 16px;
  color: #666;
}

.task-detail-container {
  flex: 1;
  width: 100%;
}

.task-checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  border: 2px solid #007aff;
  border-radius: 50%;
}

.task-checkbox.checked {
  background-color: #007aff;
}

.task-status,
.task-priority {
  padding: 2px 8px;
  font-size: 12px;
  border-radius: 10px;
}

.detail-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 0;
  border-bottom: 1px solid #e5e5ea;
}

.detail-item:last-child {
  border-bottom: none;
}

.detail-label {
  font-size: 16px;
  color: #8e8e93;
}

.detail-value {
  font-size: 16px;
  color: #000;
}

.category-tag {
  padding: 4px 12px;
  font-size: 14px;
  border-radius: 12px;
}

.attachment-item {
  display: flex;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #e5e5ea;
}

.attachment-item:last-child {
  border-bottom: none;
}

.attachment-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  margin-right: 12px;
  background-color: rgba(0, 122, 255, 0.1);
  border-radius: 8px;
}

.attachment-content {
  flex: 1;
}

.attachment-name {
  display: block;
  font-size: 16px;
  color: #000;
}

.attachment-size {
  display: block;
  font-size: 12px;
  color: #8e8e93;
}
</style>
